package org.example.leetCode;

import java.util.Stack;

/**
 * @author Administrator
 */
public class ReverseWords {
    public static void main(String[] args) {
        String s = "  hello world!  ";
        System.out.println(reverseWords(s));
    }

    public static String reverseWords(String s) {
        if ("".equals(s.trim())) {
            return "";
        }

        char[] chars = s.toCharArray();
        Stack<String> stack = new Stack<String>();
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chars) {
            if (c == ' ') {
                stack.push(String.valueOf(stringBuilder));
                stringBuilder.delete(0, stringBuilder.length());
            } else {
                stringBuilder.append(c);
            }
        }
        stack.push(String.valueOf(stringBuilder));
        stringBuilder.delete(0, stringBuilder.length());

        while (!stack.isEmpty()) {
            String pop = stack.pop();
            if ("".equals(pop)) {
                continue;
            }
            stringBuilder.append(pop);
            stringBuilder.append(' ');
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return String.valueOf(stringBuilder);
    }
}
